<template>
  <div>
    <TopFilter ref="formpanel1" :list="formList1" :cols="4" :isSubmitBtn="true" @filterChange="formchangeFun" @resetChange="resetFun" />
    <FilterTable
      ref="basetable"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :height="'200'"
      :isSelectColumn="false"
      :dataSource="toptablelist"
      :onEnterEvent="tableDbclickFun"
      selectionType="single"
      :onRowSelectChange="selectTableFun"
      columnsRef="partPartOutboundStockremovalMoveAdd"
    ></FilterTable>
    <FormPanel ref="formpanel2" :labelWidth="100" :list="formList2" :cols="4" :isSubmitBtn="false" @formChange="formchangeFuns" />
    <FilterTable
      ref="basetables"
      :columns="columns1"
      :dataSource="tablelist"
      :params="fetchParams"
      :isSelectColumn="false"
      :datakey="'rows'"
      selectionType="single"
      :onColumnsChange="columns1 => (this.columns1 = columns1)"
      :height="'200'"
      :onSyncTableData="tablechangeFun"
      columnsRef="partPartOutboundStockremovalMoveAdd1"
    ></FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9999,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button type="primary" @click="confirmHandle">保 存</el-button>
    </div>

    <!-- 库位选择弹窗 -->
    <BaseDialog :visible.sync="positionSelectVisible" title="库位选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <position :params="positionFetchParam" @close="positionSelectVisible = false" @onConfirm="handlePositionConfirm" />
      <!-- :existDataList="existDataList"
        :storageCodeKey="'NEW_STORAGE_NAME'"
        :storagePositionCodeKey="'NEW_STORAGEPOSITION_CODE'" -->
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { isAuthorized } from '@/utils/index';
import { getfindStorageCode } from '@/api/part/inventoryManager/inventoryManager/index';
import { StockParts, Storage, StockItem, getAllModel, queryUsableLocations } from '@/api/part/partOutbound/stockremoval/index';
import { getBrandList } from '@/api/common/cars/masterDataCars';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getBrand } from '@/api/repair/basicParameters';
import position from '@/pages/part/common/position';

export default {
  components: {
    position
  },
  mixins: [dictionary],
  props: ['rowData', 'existDataList'],
  data() {
    this.basetable = null;
    this.basetables = null;
    return {
      formList1: this.createFrom(),
      formList2: this.createFroms(),
      fetchApi: StockParts,
      fetchParams: {
        xhrAbort: true
      },
      SALES_PRICE: null,
      columns: this.createTable(),
      columns1: this.createTables(),
      costPrice: 0,
      tablelist: [],
      toptablelist: [],
      tableslist: [],
      listType: [],
      getpartParams: {
        // order: 'asc',
        // limit: '10',
        // queryPart_table: '',
        // dmsFuncId: '35100010',
        // _: '1565746760613',
        STORAGE_CODE: '',
        PART_NO: ''
      },
      fromSubmitdata: {},
      // 是否显示替换件按钮
      isreplace: true,
      replacedata: {},
      clickData: {},
      newStorageName: '',
      newStorageCode: '',
      partNo: '',
      storageList: [],
      locationList: [],
      defaultStorage: '',
      initStorage: null,
      positionSelectVisible: false, // 是否显示库位选择弹窗
      positionFetchParam: {}, // 库位选择查询参数
      storageItemsList: [] // 仓库列表
    };
  },
  computed: {
    storageAndPart() {
      return {
        storageCode: this.formList2.find(item => item.fieldName == 'NEW_STORAGE_CODE').initialValue,
        partNo: this.formList2.find(item => item.fieldName == 'PART_NO').initialValue
      };
    }
  },
  watch: {
    storageAndPart: {
      handler(newVal, oldVal) {
        this.formList2.find(item => item.fieldName == 'NEW_STORAGEPOSITION_CODE').disabled = !!!(newVal.partNo && newVal.storageCode);
      },
      deep: true
    }
  },
  mounted() {
    this.basetable = this.$refs.basetable.$refs.pageTable;
    this.basetables = this.$refs.basetables.$refs.pageTable;
    this.searchstore();
  },
  methods: {
    // 新仓库选择回调
    getNewStorageName(val) {
      this.newStorageName = this.storageItemsList.find(item => item.value == val).text;
      this.formList2.find(item => item.fieldName == 'NEW_STORAGEPOSITION_CODE').initialValue = '';
    },
    createFrom() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          itemList: []
        },
        // {
        //   type: 'SELECT',
        //   label: '品牌',
        //   fieldName: 'brand',
        //   itemList: []
        // },
        {
          type: 'SELECT',
          label: '仓库属性',
          fieldName: 'partType',
          itemList: this.createDictList('5000')
        },
        {
          type: 'INPUT',
          label: '配件代码',
          showOverflowTooltip: true,
          fieldName: 'PartNo'
        },
        // {
        //   type: 'INPUT',
        //   label: '拼音',
        //   fieldName: 'spellCode'
        // },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName'
        },
        {
          type: 'INPUT',
          label: '库位',
          fieldName: 'storagePositionCode'
        },
        {
          type: 'CHECKBOX',
          label: '库存大于零',
          fieldName: 'stockZero',
          options: {
            trueValue: 10041001,
            falseValue: 10041002
          }
        }
        // {
        //   type: 'CHECKBOX',
        //   label: '售价大于零',
        //   fieldName: 'priceZero',
        //   options: {
        //     trueValue: 10041001,
        //     falseValue: 10041002
        //   }
        // },
        // {
        //   type: 'INPUT',
        //   label: '备注',
        //   fieldName: 'DESCRIPTION'
        // }
      ];
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '仓库代码',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          hidden: false
        },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '终端建议零售VIP价格',
          dataIndex: 'COST_SALES_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税成本价',
          dataIndex: 'COST_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number',
          hidden: !isAuthorized('1313', '13131005')
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '备注',
          dataIndex: 'REMARK1',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createFroms() {
      return [
        {
          type: 'SELECT',
          label: '原仓库',
          fieldName: 'STORAGE_CODE',
          itemList: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '新仓库',
          fieldName: 'NEW_STORAGE_CODE',
          itemList: [],
          rules: [{ required: true, message: '请选择新仓库', trigger: 'change' }],
          change: props => {
            this.getNewStorageName(props);
          }
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'PART_NAME',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '移库数量',
          fieldName: 'TRANSFER_QUANTITY',
          rules: [{ required: true, message: '请输入移库数量', trigger: 'blur' }],
          initialValue: 1,
          precision: 2,
          change: val => {
            this.changemNum(val);
          }
        },
        {
          type: 'INPUT',
          label: '移库金额',
          fieldName: 'COST_AMOUNT',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '新库位代码',
          fieldName: 'NEW_STORAGEPOSITION_CODE',
          itemList: [],
          readonly: true,
          rules: [{ required: true, message: '请选择新库位代码', trigger: 'change' }],
          initialValue: '',
          disabled: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.handlePositionSelect}></el-button>;
          }
        }
      ];
    },
    // 选择仓库的回调,更新库存信息
    async queryEmptyLocation(val) {
      let temp = this.formList2.find(item => item.fieldName === 'NEW_STORAGEPOSITION_CODE');
      temp.initialValue = undefined;
      temp.itemList = [];
      let res = await queryUsableLocations({ storageCode: val, partNo: this.partNo });
      if (res.resultCode === 200) {
        if (res.data[0].error) {
          this.$notify.warning({ title: '提示信息', message: res.data[0].error });
          return;
        }
        console.log(res, 213123);
        if (res.data[0].newStorageName) {
          this.newStorageName = res.data[0].newStorageName;
        }
        if (res.data[0].storageName) {
          this.newStorageName = res.data[0].storageName;
        }
        this.newStorageCode = res.data[0].storageCode;
        let dataList = res.data.map(x => ({ text: x.storagePositionCode, value: x.storagePositionCode }));
        let obj = {};
        dataList = dataList.reduce((item, next) => {
          obj[next.value] ? '' : (obj[next.value] = item.push(next));
          return item;
        }, []);
        temp.itemList = dataList;
      }
    },
    createTables() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '终端建议零售VIP价格',
          dataIndex: 'COST_SALES_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '索赔价',
          dataIndex: 'CLAIM_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number',
          hidden: !isAuthorized('1313', '13131006')
        },
        {
          title: '终端建议零售价格',
          dataIndex: 'INSURANCE_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '最低销售限价',
        //   dataIndex: 'MIN_LIMIT_PRICE',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        // {
        //   title: '最高销售限价',
        //   dataIndex: 'LIMIT_PRICE',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        // {
        //   title: '最大库存',
        //   dataIndex: 'MAX_STOCK',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        // {
        //   title: '最小库存',
        //   dataIndex: 'MIN_STOCK',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_STOCK',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '锁定量',
          dataIndex: 'LOCKED_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '替代配件',
          dataIndex: 'OPTION_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.OPTION_NO ? props.row.OPTION_NO : ''}</span>;
          }
        },
        // {
        //   title: '替代件库存',
        //   dataIndex: 'OPTION_STOCK',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        {
          title: '配件属性',
          dataIndex: 'PART_TYPE',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: this.createDictList(5000),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(5000)
        },
        {
          title: '单位',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    async searchstore() {
      // 仓库下拉选
      const res = await getfindStorageCode();
      this.storageItemsList = res.data.map(x => ({
        text: x.STORAGE_NAME,
        value: x.STORAGE_CODE,
        tag: x.OEM_TAG,
        type: x.STORAGE_TYPE
      }));
      this.formList2.find(x => x.fieldName == 'NEW_STORAGE_CODE').itemList = this.formList1.find(item => item.fieldName == 'storageCode').itemList = this.storageItemsList;
      // this.formList2.find(x => x.fieldName == 'NEW_STORAGE_CODE').itemList = this.formList1.find(item => item.fieldName == 'storageCode').itemList = res.data.map(x => ({
      //   text: x.STORAGE_NAME,
      //   value: x.STORAGE_CODE,
      //   tag: x.OEM_TAG
      // }));

      let resdata = await findAllRepair();
      this.defaultStorage = resdata.data['1100'];
      // this.initStorage = this.formList1.find(item => item.fieldName === 'storageCode').initialValue = resdata.data['1100'];
      // 品牌下拉选
      // const res2 = await getBrand();
      // this.formList1.find(item => item.fieldName == 'brand').itemList = res2.data.map(x => ({ text: x.BRAND_NAME, value: x.BRAND_CODE + '' }));
      // this.formList1.find(item => item.fieldName === 'brand').initialValue = res2.data.find(item => item.BRAND_NAME == '奥迪').BRAND_CODE;
      // 配件类别下拉选
    },
    // 点击选择库位
    handlePositionSelect() {
      let partNo = this.formList2.find(item => item.fieldName == 'PART_NO').initialValue;
      let storageCode = this.formList2.find(item => item.fieldName == 'NEW_STORAGE_CODE').initialValue;

      this.positionFetchParam = {
        storageCode,
        partNo
      };
      this.positionSelectVisible = true;
    },
    // 库位选择点击确定
    handlePositionConfirm(e) {
      let storageCode = (this.formList2.find(item => item.fieldName == 'NEW_STORAGEPOSITION_CODE').initialValue = e[0].storagePositionCode);
    },
    // 重置
    resetFun() {
      this.$refs.formpanel1.RESET_FORM();
      this.$nextTick(() => {
        this.formList1.find(x => x.fieldName == 'storageCode').initialValue = this.initStorage;
      });
    },
    // 选中事件
    selectTableFun(val) {
      if (val && val.length > 0) {
        let value = val[0].OPTION_NO;
        this.replacedata = val[0];
        if (value == null) {
          this.isreplace = true;
        } else {
          this.isreplace = false;
        }
      }
    },
    formchangeFun(val) {
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
    },
    formchangeFuns(val) {
      this.fromSubmitdata = val;
    },
    // 表格双击事件
    tableDbclickFun(val) {
      // 清空上一次的值
      this.clickData = val;
      console.log('原仓库信息', val);
      this.partNo = val.PART_NO;
      this.tablelist = [];
      this.listType = val;
      this.formList2[0].initialValue = val.STORAGE_CODE;
      // console.log(this.formList2[0]);

      this.formList2[0].itemList = [{ text: val.STORAGE_NAME, value: val.STORAGE_CODE }];
      this.formList2[2].initialValue = val.PART_NO;
      this.formList2[3].initialValue = val.PART_NAME;
      this.formList2[5].initialValue = val.COST_PRICE ? this.numFilter(val.COST_PRICE) : 0;
      this.formList2.find(x => x.fieldName == 'NEW_STORAGEPOSITION_CODE').initialValue = '';
      this.costPrice = val.COST_PRICE ? this.numFilter(val.COST_PRICE) : 0;
      this.getpartlist(val);
    },
    async getpartlist(val) {
      this.getpartParams.STORAGE_CODE = val.STORAGE_CODE;
      this.getpartParams.PART_NO = val.PART_NO;
      let res = (await StockItem(this.getpartParams)).data;
      this.basetables.EXECUTE_INSERT(res);
    },
    // 保留两位小数
    numFilter(value) {
      let realVal = parseFloat(value).toFixed(2);
      return realVal;
    },
    changeMoney(val) {
      let parameter = this.formList2[4].initialValue;
      let num = this.formList2[6].initialValue;
      this.formList2[7].initialValue = parameter * val * num;
    },
    // 改变金额
    changemoney(val) {
      let parameter = this.formList2[4].initialValue;
      let num = this.formList2[5].initialValue;
      this.formList2[6].initialValue = num * parameter;
    },
    // 改变数量
    changemNum(val) {
      let money = this.costPrice;
      this.formList2[5].initialValue = (money * val).toFixed(2);
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('closeTwo', false);
    },
    tablechangeFun(val) {
      this.tableslist = val;
    },
    // 添加事件提交表单
    confirmHandle() {
      let stoList = this.formList2.find(x => x.fieldName == 'NEW_STORAGE_CODE').itemList;
      let json = this.tableslist[0];
      if (this.tableslist.length == 0) {
        return this.$notify.error({ title: '提示信息', message: '需选中一条数据' });
      }
      this.fromSubmitdata = null;
      let tempData = this.$refs.formpanel2.SUBMIT_FORM();
      // 必填字段校验
      if (!this.fromSubmitdata) return;
      let tempVal = {};
      if (this.rowData) {
        tempVal = this.rowData.find(item => item.NEW_STORAGE_CODE == tempData.NEW_STORAGE_CODE);
      }
      if (tempVal) {
        if (tempVal.NEW_STORAGEPOSITION_CODE == tempData.NEW_STORAGEPOSITION_CODE) {
          return this.$notify.warning({ title: '错误提示', message: '该库位已被占用' });
        }
      }
      let formdata = Object.assign({}, json, this.fromSubmitdata);
      if (this.formList2.find(x => x.fieldName === 'NEW_STORAGE_CODE').initialValue === undefined) {
        return this.$notify.warning({ title: '提示信息', message: '新仓库必填,不能为空' });
      }
      if (this.formList2.find(x => x.fieldName === 'NEW_STORAGE_CODE').initialValue === this.formList2.find(x => x.fieldName === 'STORAGE_CODE').initialValue) {
        return this.$notify.warning({ title: '提示信息', message: '新旧仓库不能一样' });
      }
      // OEMK
      if (this.clickData.OEM_TAG != stoList.find(x => x.value == this.fromSubmitdata.NEW_STORAGE_CODE).tag) {
        return this.$notify.warning({ title: '警告', message: '主机厂库与店面库之间不能移库' });
      }
      console.log(this.clickData.STORAGE_TYPE, '1', stoList.find(x => x.value == this.fromSubmitdata.NEW_STORAGE_CODE).type, '2');
      // if (this.clickData.STORAGE_TYPE != stoList.find(x => x.value == this.fromSubmitdata.NEW_STORAGE_CODE).type) {
      //   return this.$notify.warning({ title: '警告', message: '油车件库与电车件库之间不能移库' });
      // }
      // if (this.formList2.find(x => x.fieldName === 'NEW_STORAGE_CODE').initialValue === 'OEMK') {
      //   return this.$notify.warning({ title: '警告', message: '不能移到OEM仓库' });
      // }
      if (
        this.formList2.find(x => x.fieldName === 'TRANSFER_QUANTITY').initialValue >
        this.clickData.STOCK_QUANTITY + this.clickData.BORROW_QUANTITY - this.clickData.LOCKED_QUANTITY - this.clickData.LEND_QUANTITY
      ) {
        return this.$notify.warning({ title: '提示信息', message: '移库数量不能大于可用库存' });
      }
      formdata.OLD_STORAGEPOSITION_CODE = formdata.STORAGE_POSITION_CODE;
      formdata.OLD_STORAGE_CODE = formdata.STORAGE_CODE;
      formdata.OLD_STORAGE_NAME = this.clickData.STORAGE_NAME;
      formdata.NEW_STORAGEPOSITION_CODE = this.fromSubmitdata.NEW_STORAGEPOSITION_CODE;
      formdata.NEW_STORAGE_CODE = this.fromSubmitdata.NEW_STORAGE_CODE;
      formdata.NEW_STORAGE_NAME = this.newStorageName;
      console.log(formdata, 'formdata');
      // this.rowData.push(formdata);
      this.$emit('changedata', formdata);
      // return this.$notify.success({ title: '提示信息', message: '添加成功！' });
    }
  }
};
</script>
